package action

import (
	"gitee.com/sansaniot/ssiot-core/facade/env"
	"gorm.io/gorm"

	"ssforward/common/constant"
	"ssforward/common/utils"
	"ssforward/internal/data/handler"
)

type Handle struct {
	Orm *gorm.DB
}

func (action *Handle) Execute(topic string, jsonData map[string]interface{}) {
	sn := jsonData["sn"].(string)
	if _, ok := constant.HasForwardConfigSn.Load(sn); !ok {
		return
	}
	cacheForwardConfig, _ := env.Cache.Get(constant.ForwardConfigKey + sn)
	if len(cacheForwardConfig) == 0 {
		return
	}
	configList := utils.BytesToMapArr([]byte(cacheForwardConfig))
	for _, configMap := range configList {
		serverType := ""
		if tp, ok := configMap["serverType"]; ok && tp != nil {
			serverType = tp.(string)
		}
		copyMap := utils.BytesToMap(utils.MapToBytes(jsonData))
		handler.GetHandlerCtrl(serverType).ForwardFunc(action.Orm, configMap, copyMap)
	}
}
